<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('估值方法')" prop="method">
            <el-input v-model="form.method" :placeholder="$t('估值方法')" show-word-limit maxlength="10" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('状态')">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ dict.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.code === 'pe' || form.code === 'pb'" :span="24">
          <el-form-item :label="form.code === 'pe' ? $t('主营业务利润获取公式') : $t('总资产获取公式')" prop="formula">
            <el-autocomplete
              v-model="form.formula"
              class="inline-input"
              :placeholder="form.code === 'pe' ? $t('主营业务利润获取公式') : $t('总资产获取公式')"
              readonly
              :trigger-on-focus="false"
              @select="selectGS"
            >
              <template slot="append" @click="selectGS">
                <a @click="selectGS">{{ $t('选择公式') }}</a>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="form.code === 'pe' || form.code === 'pb'">
        <div class="area-header" style="margin-top: 10px;">
          <span class="area-header-title">{{ $t('对标公司信息') }}</span>
        </div>
        <div>
          <el-tag
            v-for="dict in industryOption"
            :key="dict.id"
            style="margin-right: 5px;cursor: pointer;margin-bottom: 10px;-webkit-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;"
            :type="selectTagName === dict.dictValue ? '' : 'info'"
            @click="selectTag(dict)"
          >{{ dict.dictLabel }}</el-tag>
        </div>
        <el-table tooltip-effect="darkTable" :data="form.dealValuationSettingStockList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('股票代码')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('股票代码') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealValuationSettingStockList.' + scope.$index + '.stockCode'" :rules="dealValuationSettingStockRules.stockCode">
                <el-input v-model="scope.row.stockCode" show-word-limit :maxlength="100" :placeholder="$t('股票代码')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('股票名称')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('股票名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealValuationSettingStockList.' + scope.$index + '.stockName'" :rules="dealValuationSettingStockRules.stockName">
                <el-input v-model="scope.row.stockName" show-word-limit :maxlength="100" :placeholder="$t('股票名称')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('适用行业')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('适用行业') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealValuationSettingStockList.' + scope.$index + '.industry'" :rules="dealValuationSettingStockRules.industry">
                <FocusIndustry :industry-data="scope.row.industryList" @industryFocusList="getIndustryFocusList($event, scope.row)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" align="center" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="delStock(scope.$index, scope.row)">{{ $t('删除') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addStock">
            {{ $t('添加') }}
          </el-button>
        </div>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn />
    </div>

    <!-- 添加或修改关键指标公式（系统模板）对话框 -->
    <el-dialog v-if="!isEmpty(typeId)" v-el-drag-dialog :title="$t('选择公式')" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogPcw" append-to-body>
      <pcwTempKeyFormula ref="pcwTempKeyFormula" :formula="formula" :is-sys-temp="true" :type-id="typeId" :show-date="false" />
    </el-dialog>
  </div>
</template>

<script>
import {
  saveDealValuationSetting,
  getDealValuationSetting,
  delDealValuationSettingStock
} from '@/api/deal/analysisValuation/dealValuationSetting'
import pcwTempKeyFormula from '@/views/company/pcw/pcwTempKeyFormula.vue'
import { listPcwSysType } from '@/api/company/pcw/pcwSysType'
export default {
  components: {
    pcwTempKeyFormula
  },
  data() {
    return {
      // 表单参数
      form: {
        dealValuationSettingStockList: []
      },
      // 遮罩层
      loading: false,
      statusOptions: [],
      // 表单校验
      rules: {
        method: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        status: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      dealValuationSettingStockRules: {
        stockCode: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      formOpen: false,
      formula: {},
      typeId: '',
      tagList: [],
      selectTagName: '',
      industryOption: []
    }
  },
  watch: {
  },
  created() {
    this.getDicts('deal_valuation_setting_status').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('deal_industry_focus').then(response => {
      this.industryOption = response.data
    })
    // 获取
    listPcwSysType({ pageNum: 1, pageSize: 1 }).then(response => {
      if (response.rows) {
        this.typeId = response.rows[0].id
      }
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getDealValuationSetting(data.id).then(response => {
          this.form = response.data
          this.form.dealValuationSettingStockListTemp = JSON.parse(JSON.stringify(this.form.dealValuationSettingStockList))
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        method: undefined,
        status: undefined,
        formula: undefined,
        formulaFormat: undefined,
        industryList: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        dealValuationSettingStockList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    addStock() {
      const row = {
        id: undefined,
        parentId: this.form.id,
        stockCode: '',
        stockName: '',
        industryFirst: '',
        industrySecond: ''
      }
      if (!(this.form.dealValuationSettingStockList instanceof Array)) {
        this.$set(this.form, 'dealValuationSettingStockList', [])
      }
      this.$nextTick(() => {
        this.form.dealValuationSettingStockList.push(row)
        this.form.dealValuationSettingStockListTemp = JSON.parse(JSON.stringify(this.form.dealValuationSettingStockList))
      })
    },
    delStock(index, row) {
      if (this.isEmpty(row.id)) {
        this.form.dealValuationSettingStockList.splice(index, 1)
        this.form.dealValuationSettingStockListTemp = JSON.parse(JSON.stringify(this.form.dealValuationSettingStockList))
      } else {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(function() {
          return delDealValuationSettingStock(row.id)
        }).then(() => {
          this.form.dealValuationSettingStockList.splice(index, 1)
          this.form.dealValuationSettingStockListTemp = JSON.parse(JSON.stringify(this.form.dealValuationSettingStockList))
          this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
      }
    },
    // 获取聚焦行业数据
    getIndustryFocusList(val, row) {
      row.industryFirst = val[0]
      if (val[1]) {
        row.industrySecond = val[1]
      } else {
        row.industrySecond = ''
      }
    },
    /** 选择公式操作 */
    selectGS() {
      this.formOpen = true
      this.formula = {
        name: this.form.formula,
        code: this.form.formulaFormat
      }
    },
    /** 获取公式值 **/
    addFormula(name, code, formulaList) {
      console.log(name, code, formulaList)
      this.form.formula = name
      this.form.formulaFormat = code
      this.form.formulaJson = JSON.stringify(formulaList)
    },
    selectTag(dict) {
      var tempFlag = false
      this.form.dealValuationSettingStockList.forEach(item => {
        if (this.isEmpty(item.id)) {
          tempFlag = true
        }
      })
      if (tempFlag) {
        var _this = this
        this.$confirm(this.$t('您填写的内容尚未保存, 是否继续?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(() => {
          _this.selectTagStart(dict)
        }).then(() => {
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.selectTagStart(dict)
      }
    },
    /** 筛选标签 **/
    selectTagStart(dict) {
      if (this.selectTagName === dict.dictValue) {
        this.selectTagName = ''
        this.form.dealValuationSettingStockList = JSON.parse(JSON.stringify(this.form.dealValuationSettingStockListTemp))
      } else {
        this.selectTagName = dict.dictValue
        this.form.dealValuationSettingStockList = JSON.parse(JSON.stringify(this.form.dealValuationSettingStockListTemp))
        var arr = []
        this.form.dealValuationSettingStockList.forEach(item => {
          if (item.industryFirst === dict.dictValue) {
            arr.push(item)
          }
        })
        this.form.dealValuationSettingStockList = arr
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveDealValuationSetting(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>
